package com.gitee.ixtf.cqrs.verticle

import com.gitee.ixtf.core.J
import com.gitee.ixtf.cqrs.kotlinx.ENTITY_ID_KEY
import com.gitee.ixtf.vertx.verticle.BaseCoroutineVerticle
import io.vertx.core.Future

abstract class KeyValueEntity<S> : BaseCoroutineVerticle() {
  protected val entityId: String by lazy { config.getString(ENTITY_ID_KEY) }
  private var currentState: S? = null

  fun invalidate(): Future<Void> =
      if (J.nonBlank(deploymentID)) vertx.undeploy(deploymentID) else Future.succeededFuture()

  protected fun currentState(): S = currentState!!

  protected abstract suspend fun emptyState(): S

  protected abstract suspend fun persist(entity: S): S

  override suspend fun start() {
    super.start()
    currentState = emptyState()
  }
}
